/*
 * commons is a based project implemented
 * Copyright (C) 2024 Jasmine
 */
package com.commons.apidoc.config;

import org.springdoc.core.customizers.OperationCustomizer;
import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.commons.apidoc.props.SwaggerProperties;

import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.models.ExternalDocumentation;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.parameters.Parameter;

/**
 * SpringDoc API文档相关配置
 */
@Configuration
@EnableConfigurationProperties(SwaggerProperties.class)
public class SpringDocConfig {

    @Autowired
    private SwaggerProperties swaggerProperties;

    /**
     * 定义 多个包之间分隔符
     */
    private static final String SEPARATOR = ",";

    @Bean
    public OpenAPI openAPI() {
        return new OpenAPI()
            .info(new Info().title("服务接口 API").description("SpringDoc API").version("v1.0.0")
                .contact(new Contact().name("jasmine"))
                .license(new License().name("jasmine").url("https://springdoc.org/")))
            .externalDocs(new ExternalDocumentation().description("Interface Documentation").url("项目地址"));
    }

    /**
     * 配置一个所有接口组
     */
    @Bean
    public GroupedOpenApi allApi() {
        return GroupedOpenApi.builder().group("所有接口").packagesToScan("com")
            .addOperationCustomizer(operationCustomizer()).build();
    }

    /**
     * 配置一个自定义组
     */
    @Bean
    @ConditionalOnProperty(prefix = "springdoc", name = "basePackages")
    public GroupedOpenApi publicApi() {
        String[] packages = swaggerProperties.getBasePackages().split(SEPARATOR);
        return GroupedOpenApi.builder().group(swaggerProperties.getGroupName()).packagesToScan(packages).build();
    }

    /**
     * 给所有@Operation注释的接口添加一个Authorication请求头参数
     */
    @Bean
    public OperationCustomizer operationCustomizer() {
        return (operation, handlerMethod) -> {
            operation.addParametersItem(new Parameter().in(ParameterIn.HEADER.toString()).name("Authorication")
                .description("登录用户账号").schema(new StringSchema()).example("1111111111111111111111").required(false));
            return operation;
        };
    }
}